package com.jinlingxiu.app.mvp.presenter

import android.app.Activity
import android.graphics.Bitmap
import android.os.Environment
import com.blankj.utilcode.util.*
import com.jinlingxiu.app.mvp.contract.PassContract
import com.jinlingxiu.app.other.db.database.DatabaseManager
import com.xdja.easymvp.mvp.BasePresenter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

/**
 * 描述:
 * Create by yuanwanli
 * Date 2020/09/11
 */
class PassPresenter(model: PassContract.Model, rootView: PassContract.View) :
    BasePresenter<PassContract.Model, PassContract.View>(model, rootView) {
    fun getUserInfo() {
        launch {
            val loadAllUsers = DatabaseManager.getInstance(Utils.getApp())
                .userInfoDao()
                .loadAllUsers()
            if (loadAllUsers.isNotEmpty()) {
                mRootView?.showUser(loadAllUsers[0])
            }
        }
    }

    fun saveScreen(activity: Activity) {
        launch {
            val withContext = withContext(Dispatchers.IO) {
                val screenShot = ScreenUtils.screenShot(activity)
                val appDir =
                    File(Environment.getExternalStorageDirectory(), "pass")
                if (!appDir.exists()) {
                    appDir.mkdir()
                }
                val fileName = TimeUtils.getNowMills().toString() + ".jpeg"
                val file = File(appDir, fileName)
                val save = ImageUtils.save(screenShot, file, Bitmap.CompressFormat.JPEG)
                if (save) {
                    FileUtils.notifySystemToScan(file)
                }
                save
            }
            if (withContext) {
                mRootView?.showMessage("保存成功")
            } else {
                mRootView?.showMessage("保存失败")
            }
        }
    }
}
